/*
 * Copyright 2012-2019 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.samples.petclinic.owner;

import java.util.List;

import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

/**
 * @author Juergen Hoeller
 * @author Mark Fisher
 * @author Ken Krebs
 * @author Arjen Poutsma
 */
@Controller
class VisitsController {

	private final VisitRepository visitRepository;

	public VisitsController(VisitRepository clinicService) {
		this.visitRepository = clinicService;
	}

	@GetMapping("/visits.html")
	public String showVisitList(@RequestParam(defaultValue = "1") int page, Model model) {
		// Here we are returning an object of type 'Visits' rather than a collection of
		// Visit
		// objects so it is simpler for Object-Xml mapping
		// 这里我们返回一个Visits类型的对象，而不是Visit的集合
		// 对象，因此对象-Xml映射更简单
		Visits visits = new Visits();
		System.out.println("1\n2\n3\n" + visits);
		Page<Visit> paginated = findPaginated(page);
		visits.getVisitList().addAll(paginated.toList());
		return addPaginationModel(page, paginated, model);

	}

	private String addPaginationModel(int page, Page<Visit> paginated, Model model) {
		List<Visit> listVisits = paginated.getContent();
		System.out.println("1\n2\n456\n" + listVisits);
		System.out.println(listVisits.iterator().next().getDescription());
		model.addAttribute("currentPage", page);
		model.addAttribute("totalPages", paginated.getTotalPages());
		model.addAttribute("totalItems", paginated.getTotalElements());
		model.addAttribute("listVisits", listVisits);
		return "visitView";
	}

	private Page<Visit> findPaginated(int page) {
		int pageSize = 5;
		Pageable pageable = PageRequest.of(page - 1, pageSize);
		return visitRepository.findAll(pageable);
	}

	@GetMapping({ "/visits" })
	public @ResponseBody Visits showResourcesVisitList() {
		// Here we are returning an object of type 'Visits' rather than a collection of
		// Visit
		// objects so it is simpler for JSon/Object mapping
		Visits visits = new Visits();
		visits.getVisitList().addAll(this.visitRepository.findAll());
		return visits;
	}

}
